﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using DeepEarth.Core;
using DeepEarth.Core.Utilities;
using DeepEarth.Map.Core.Utilities;

#if !WINDOWS_PHONE
using System.Json;
using System.Reactive.Linq;
#endif

namespace DeepEarth.Map.TileSources
{
	public sealed class NearMapPhotoDate
	{
#if !WINDOWS_PHONE
        public static IObservable<IEnumerable<DateTime>> GetDates(Location centre)
		{
			var url = GetUrl(centre);
			return WebRequestHelper.RequestUrl(url)
				.Select(ParseDates);
		}

		private static IEnumerable<DateTime> ParseDates(string jsonResponse)
		{
			var result = JsonValue.Parse(jsonResponse);

			int[] i;

			return DateTime.MaxValue.Date
				.Concat(((JsonArray) result["layers"]["Vert"]).Select(ParseJsonDate))
				.OrderByDescending(d => d)
				.ToArray();
		}

        static DateTime ParseJsonDate(JsonValue value)
		{
			return new DateTime(1970, 1, 1).AddMilliseconds(long.Parse(Regex.Match(value, @"\d+").Value));
		}
#endif

        private static string GetUrl(Location centre)
		{
			const int zoomLevel = 18;
			var logicalCentre = CoordinateTransformation.GeographicToLogical(centre);
			var x = (int)(logicalCentre.X * Math.Pow(2, zoomLevel));
			var y = (int)(logicalCentre.Y * Math.Pow(2, zoomLevel));
			return string.Format("http://www.nearmap.com/maps/x={0}&y={1}&z={2}&nmq=info&nmf=json", x, y, zoomLevel);
		}


	}
}
